"""
应用PCA降维算法处理鸢尾花数据集重新根据降维数据选择合适模型进行训练和预测，
要求：输出训练得分、预测得分，并对表格鸢尾花数据进行预测（分值：30；结果：截图呈现图片命令为图6，代码命名5.py，）
"""
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

iris = load_iris()
x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)
pca = PCA(n_components=2)
x_train_pca = pca.fit_transform(x_train)

x_test_pca = pca.transform(x_test)
model = LogisticRegression()
model.fit(x_train_pca, y_train)
y_train_predict = model.predict(x_train_pca)
train_score = accuracy_score(y_train, y_train_predict)
y_test_predict = model.predict(x_test_pca)
test_score = accuracy_score(y_test, y_test_predict)
print("训练得分:", train_score)
print("预测得分:", test_score)

new_data = pd.read_csv('iris.csv')
new_data = new_data.sample(frac=1, replace=False, random_state=42)  # 随机打乱顺序
# 前几列是特征数据，最后一列是标签列
X_new = new_data.iloc[:12, :4].values  # 提取特征数据部分(仅取前12列作为示例)
# print(X_new.shape)
X_new_pca = pca.transform(X_new)

# 使用训练好的模型对新数据进行预测
new_predictions = model.predict(X_new_pca)
# print(new_predictions)
# 获取鸢尾花类别名称（假设格式与sklearn的鸢尾花数据集一致）
target_names = iris.target_names
result = [target_names[predict] for predict in new_predictions]
# 输出新数据的预测结果（以类别名称形式展示更直观）
print("新数据的预测结果:", result)
